package com.telecom.sxint.app.core.service.impl.Vatinvoince;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.zjtele.pubinfo.common.http.response.ResponseData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.telecom.sxint.app.core.domain.entity.Vatinvoicepojo.App1Vatinvoinceprintlog;
import com.telecom.sxint.app.core.domain.entity.Query.PageData;
import com.telecom.sxint.app.core.domain.entity.dto.InvoiceFilterDTO;
import com.telecom.sxint.app.core.domain.entity.dto.TicketQueryDTO;
import com.telecom.sxint.app.core.mapper.Vatinvoincemapper.App1VatinvoinceprintlogMapper;
import com.telecom.sxint.app.core.service.Vatinvoiceservice.IApp1VatinvoinceprintlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2024-08-07
 */
@Service
public class App1VatinvoinceprintlogServiceImpl extends ServiceImpl<App1VatinvoinceprintlogMapper, App1Vatinvoinceprintlog> implements IApp1VatinvoinceprintlogService {
    @Autowired
    private App1VatinvoinceprintlogMapper app1VatinvoinceprintlogMapper;

    /**
     * 文件单记录上传
     * @param app1Vatinvoinceprintlog
     * @return
     */
    @Override
    public ResponseData handleSingleUpload(App1Vatinvoinceprintlog app1Vatinvoinceprintlog) {
        String area = app1Vatinvoinceprintlog.getArea();

        String printmonth = app1Vatinvoinceprintlog.getPrintmonth();
        String billmonth = app1Vatinvoinceprintlog.getBillmonth();
        //判断打印周期或专票周期格式是否正确
        if(!StrUtil.isBlank(printmonth)){
            if(!printmonth.matches("^(19|20)\\d{2}(0[1-9]|1[0-2])$")||printmonth.length()!=6){
                return ResponseData.failed("打印周期格式错误，例：202408","410003");
            }
        }else {
            app1Vatinvoinceprintlog.setPrintmonth("");
        }
        if(!StrUtil.isBlank(billmonth)){
            if(!billmonth.matches("^(19|20)\\d{2}(0[1-9]|1[0-2])$")||billmonth.length()!=6){
                return ResponseData.failed("专票周期格式错误，例：202408","410003");
            }
        }else {
            app1Vatinvoinceprintlog.setBillmonth("");
        }
        String account = app1Vatinvoinceprintlog.getAccount();
        String invoice = app1Vatinvoinceprintlog.getInvoice();
        //判断account和invoice至少一个不是空
        if(StrUtil.isBlank(account) && StrUtil.isBlank(invoice)){
            return ResponseData.failed("合同号和专票流水号至少填写一个","410003");
        }

        String created = app1Vatinvoinceprintlog.getCreated();
        if(!created.matches("^(19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])$")){
            return ResponseData.failed("创建日期格式错误，例：20240110","410003");
        }

        String amount = app1Vatinvoinceprintlog.getAmount();
        app1Vatinvoinceprintlog.setPrintflag("否");
        String operator = app1Vatinvoinceprintlog.getOperator();
        int insert = app1VatinvoinceprintlogMapper.Single(app1Vatinvoinceprintlog);
        if(insert!=1){
            return ResponseData.failed("导入失败","410003");
        }
        return ResponseData.success("导入成功");
    }

    /**
     * 修改专票
     * @param app1Vatinvoinceprintlog
     * @return
     */
    @Override
    public App1Vatinvoinceprintlog updateByIdrdate(App1Vatinvoinceprintlog app1Vatinvoinceprintlog) {
        app1VatinvoinceprintlogMapper.updateById(app1Vatinvoinceprintlog);
        App1Vatinvoinceprintlog log1 = app1VatinvoinceprintlogMapper.selectById(app1Vatinvoinceprintlog.getId());

        return log1;
    }
    /**
     * 根据组织分页查询
     * @param ticketQueryDTO
     * @return
     */
    @Override
    public PageData queryAreaTicketPage(TicketQueryDTO ticketQueryDTO,String area) {
        Page<App1Vatinvoinceprintlog> page = Page.of(ticketQueryDTO.getCurrentPage(), ticketQueryDTO.getPageSize());
        //排序  page.addOrder(new OrderItem(ticketQueryDTO.))
        //2分页查询
        Page<App1Vatinvoinceprintlog> p = lambdaQuery()
                .eq(App1Vatinvoinceprintlog::getArea, area)
                .eq(App1Vatinvoinceprintlog::getIsDelete, 0) // 确保只查询 is_delete 字段为 0 的记录
                .page(page);
        //3封装VO结果
        PageData<App1Vatinvoinceprintlog> dto = new PageData<>();
        //总条数
        dto.setTotal(p.getTotal());
        //当前页
        dto.setCurrentPage(p.getCurrent());
        dto.setPageSize(p.getSize());
        dto.setRecords(p.getRecords());
        //4返回
        return dto;
    }
    /**
     * 修改打印状态，是/否
     * @param ids
     * @return
     */
    @Override
    public ResponseData updatePrintflag(List<Integer> ids) {
        if(ids.isEmpty()){
            return ResponseData.failed("未选择记录","4001");
        }
        for (Integer id:ids){
            App1Vatinvoinceprintlog app1Vatinvoinceprintlog = app1VatinvoinceprintlogMapper.selectById(id);
            if(app1Vatinvoinceprintlog.getPrintflag().equals("是")||app1Vatinvoinceprintlog.getPrintflag().equals("true")){
                app1Vatinvoinceprintlog.setPrintflag("否");
            }else if (app1Vatinvoinceprintlog.getPrintflag().equals("否")||app1Vatinvoinceprintlog.getPrintflag().equals("false")){
                app1Vatinvoinceprintlog.setPrintflag("是");
            }else {
                return ResponseData.failed("打印状态错误","4001");
            }
            app1VatinvoinceprintlogMapper.updateById(app1Vatinvoinceprintlog);
        }
        return ResponseData.success("修改成功");
    }
    /**
     * 查询专票
     * @param filter
     * @return
     */
    @Override
    public List<App1Vatinvoinceprintlog> findInvoicesByFilter(InvoiceFilterDTO filter) {

        return lambdaQuery()
                .eq(App1Vatinvoinceprintlog::getIsDelete,0)
                .eq(filter.getPrintflag() != null, App1Vatinvoinceprintlog::getPrintflag, filter.getPrintflag())
                .eq(filter.getArea() != null, App1Vatinvoinceprintlog::getArea, filter.getArea())
                .eq(filter.getAccount() != null, App1Vatinvoinceprintlog::getAccount, filter.getAccount())
                .eq(filter.getPrintmonth() != null, App1Vatinvoinceprintlog::getPrintmonth, filter.getPrintmonth())
                .eq(filter.getInvoice() != null, App1Vatinvoinceprintlog::getInvoice, filter.getInvoice())
                .eq(filter.getOperator() != null, App1Vatinvoinceprintlog::getOperator, filter.getOperator())
                .eq(filter.getCreated() != null, App1Vatinvoinceprintlog::getCreated, filter.getCreated())
                .eq(filter.getBillmonth() != null, App1Vatinvoinceprintlog::getBillmonth, filter.getBillmonth())
                .orderByDesc(App1Vatinvoinceprintlog::getCreated).list();
    }
    /**、
     * 关键字搜索专票
     * @param keyword
     * @return
     */
    @Override
    public List<App1Vatinvoinceprintlog> searchByKeyword(String keyword) {
        QueryWrapper<App1Vatinvoinceprintlog> queryWrapper = new QueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.eq("is_delete",0)// 只查询 is_delete 字段为 0 的记录
                    .like("area", keyword)
                    .or().like("account", keyword)
                    .or().like("printmonth", keyword)
                    .or().like("invoice", keyword)
                    .or().like("amount", keyword)
                    .or().like("printflag", keyword)
                    .or().like("operator", keyword)
                    .or().like("created", keyword)
                    .or().like("billmonth", keyword);
        }
        return app1VatinvoinceprintlogMapper.selectList(queryWrapper);
    }
    /**
     *根据组织关键字查询专票
     * @param keyword
     * @param area
     * @return
     */
    @Override
    public List<App1Vatinvoinceprintlog> searchByKeyword2(String keyword, String area) {
        QueryWrapper<App1Vatinvoinceprintlog> queryWrapper = new QueryWrapper<>();

        // 确保指定的组织（area）非空，并首先匹配 area 字段
        if (area != null && !area.isEmpty()) {
            queryWrapper.eq("area", area);
        }

        // 如果 keyword 非空，则在指定的组织下进行模糊搜索
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.and(wrapper -> wrapper.eq("is_delete",0)// 只查询 is_delete 字段为 0 的记录
                    .like("account", keyword)
                    .or().like("printmonth", keyword)
                    .or().like("invoice", keyword)
                    .or().like("amount", keyword)
                    .or().like("printflag", keyword)
                    .or().like("operator", keyword)
                    .or().like("created", keyword)
                    .or().like("billmonth", keyword)
            );
        }

        // 按创建时间降序排列
        queryWrapper.orderByDesc("created");

        return list(queryWrapper);
    }
    /**
     * 删除专票
     * @param id
     */
    @Override
    public void DeleteById(Integer id) {
        app1VatinvoinceprintlogMapper.deleteById(id);
    }
    /**
     * 清空专票表
     */
    @Override
    public void deleteAll() {
        app1VatinvoinceprintlogMapper.delete(null);
    }

    /**
     * 导出专篇id查询
     * @param ids
     * @return
     */
    @Override
    public List<App1Vatinvoinceprintlog> findByIds(List<Integer> ids) {
        List<App1Vatinvoinceprintlog> list = app1VatinvoinceprintlogMapper.selectBatchIds(ids);
        return list;
    }
    /**
     * 生成excel
     * @param results
     * @return
     */
    public Workbook ExportUtil(List<App1Vatinvoinceprintlog> results) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("App1Vatinvoinceprintlog");
        // 创建标题行
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("id");
        headerRow.createCell(1).setCellValue("area");
        headerRow.createCell(2).setCellValue("account");
        headerRow.createCell(3).setCellValue("printmonth");
        headerRow.createCell(4).setCellValue("invoice");
        headerRow.createCell(5).setCellValue("amount");
        headerRow.createCell(6).setCellValue("printflag");
        headerRow.createCell(7).setCellValue("operator");
        headerRow.createCell(8).setCellValue("created");
        headerRow.createCell(9).setCellValue("billmonth");
        int rowNum = 1;
        for (App1Vatinvoinceprintlog app1Vatinvoinceprintlog : results) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(app1Vatinvoinceprintlog.getId());
            row.createCell(1).setCellValue(app1Vatinvoinceprintlog.getArea());
            row.createCell(2).setCellValue(app1Vatinvoinceprintlog.getAccount());
            row.createCell(3).setCellValue(app1Vatinvoinceprintlog.getPrintmonth());
            row.createCell(4).setCellValue(app1Vatinvoinceprintlog.getInvoice());
            row.createCell(5).setCellValue(app1Vatinvoinceprintlog.getAmount());
            row.createCell(6).setCellValue(app1Vatinvoinceprintlog.getPrintflag());
            row.createCell(7).setCellValue(app1Vatinvoinceprintlog.getOperator());
            row.createCell(8).setCellValue(app1Vatinvoinceprintlog.getCreated());
            row.createCell(9).setCellValue(app1Vatinvoinceprintlog.getBillmonth());
        }
        return workbook;
    }
    /**
     * 导出部分记录
     */
    @Override
    public void exportExcel(List<Integer> ids,HttpServletResponse response)  {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        App1Vatinvoinceprintlog app1Vatinvoinceprintlog=new App1Vatinvoinceprintlog();
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMM");
        String formattedDate2 = currentDate.format(formatter2);
        //根据id修改打印状态为是
        for (Integer id:ids){
            app1Vatinvoinceprintlog=app1VatinvoinceprintlogMapper.selectById(id);
            app1Vatinvoinceprintlog.setPrintflag("是");
            app1Vatinvoinceprintlog.setPrintmonth(formattedDate2);
            app1VatinvoinceprintlogMapper.updateById(app1Vatinvoinceprintlog);
        }
        Workbook workbook = null;
        String fileName = "App1Vatinvoinceprintlog";
        String fileExtension = ".xlsx";

        // 获取当前日期和时间，并格式化为字符串
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String formattedDate = now.format(formatter);

        // 设置响应内容类型和文件名
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + "_" + formattedDate + fileExtension);
        List<App1Vatinvoinceprintlog> results = findByIds(ids);
        try (OutputStream outputStream = response.getOutputStream()) {
            workbook = ExportUtil(results);
            workbook.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("Export failed", e);
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    log.error("Failed to close workbook", e);
                }
            }
        }
    }
    /**
     * 导出所有记录
     */
    @Override
    public void exportAllExcel(HttpServletResponse response) {
        //只导出字段is_delete=0的数据
        QueryWrapper<App1Vatinvoinceprintlog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        List<App1Vatinvoinceprintlog> results = app1VatinvoinceprintlogMapper.selectList(queryWrapper);
        if (results == null || results.isEmpty()) {
            return;
        }
        App1Vatinvoinceprintlog app1Vatinvoinceprintlog=new App1Vatinvoinceprintlog();
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMM");
        String formattedDate2 = currentDate.format(formatter2);
        //根据id修改打印状态为是
        for (App1Vatinvoinceprintlog app1Vatinvoinceprintlog1:results){
            app1Vatinvoinceprintlog1.setPrintflag("是");
            app1Vatinvoinceprintlog1.setPrintmonth(formattedDate2);
            app1VatinvoinceprintlogMapper.updateById(app1Vatinvoinceprintlog1);
        }
        Workbook workbook = null;
        String fileName = "App1Vatinvoinceprintlog";
        String fileExtension = ".xlsx";

        // 获取当前日期和时间，并格式化为字符串
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String formattedDate = now.format(formatter);

        // 设置响应内容类型和文件名
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + "_" + formattedDate + fileExtension);

        try (OutputStream outputStream = response.getOutputStream()) {
            workbook = ExportUtil(results);
            workbook.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("Export failed", e);
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    log.error("Failed to close workbook", e);
                }
            }
        }
    }
    /**
     * 根据组织分页查询
     * @param ticketQueryDTO
     * @return
     */
    @Override
    public PageData queryTicketPage(TicketQueryDTO ticketQueryDTO) {
        //1构建查询条件
        Page<App1Vatinvoinceprintlog> page = Page.of(ticketQueryDTO.getCurrentPage(), ticketQueryDTO.getPageSize());
        //排序  page.addOrder(new OrderItem(ticketQueryDTO.))
        //2分页查询
        Page<App1Vatinvoinceprintlog> p = lambdaQuery()
                .eq(App1Vatinvoinceprintlog::getIsDelete, 0) // 确保只查询 is_delete 字段为 0 的记录
                .page(page);
        //3封装VO结果
        PageData<App1Vatinvoinceprintlog> dto = new PageData<>();
        //总条数
        dto.setTotal(p.getTotal());
        //当前页
        dto.setCurrentPage(p.getCurrent());
        dto.setPageSize(p.getSize());
        dto.setRecords(p.getRecords());
        //4返回
        return dto;
    }
}
